<template>
<view class="container" :style="'height:' + (ProductshowWay==1? '100%':'')"> 
<!-- 头部 -->
 <view class="typeSearchContainer"> 
    <!-- <view class='search_input_bg'>
      <view class='search_input'>
        <view class='search_input_left'>
          <image class='input_img' src='http://image1.sansancloud.com/xianhua/2018_9/14/16/25/0_222.jpg?x-oss-process=style/preview_120'></image>
          <input class='input' bindconfirm='getSearchShopName' value='{{shopName}}'  bindinput="searchShopValue" placeholder='搜索店铺名'></input>
        </view>
        <view class='empty_button' bindtap='getSearchShopName'><text>x</text></view>
      </view>
    </view> -->
    <view class="typeSearch">
     <view class="flexCenter" data-index="0" style="width:85%">
       <scroll-view scroll-x class="tab-h" :scroll-into-view="'tab_'+positionTab" scroll-with-animation="true">
         <view v-for="(type, index) in venueType" :key="index" :data-type="type" @tap="bindTypeItem" :id="'tab_'+type.id" class="tab-item" :style="'color:' + type.colorAtive + ';border-bottom:' + (type.active?'4rpx solid '+type.colorAtive:'') + ';font-size:' + (type.active?'32rpx':'28rpx')">{{type.name}}</view>
       </scroll-view>
     </view>
    
     <view class="flexCenter" @tap="toMy" style="width:100rpx">
        <view class="border_left"></view>
        <image src="http://image1.sansancloud.com/xianhua/2019_7/4/10/22/8_397.jpg?x-oss-process=style/preview_120"></image>
     </view>
    </view>
  </view>


    <!-- <block wx:if='{{ProductshowWay == 2}}' >
     <view class='product_page_container2' style='height:{{ProductshowWay==1? "100%":""}}'>
        <block wx:if = "{{!! productData}}">
          <view class='product_items2' data-info='{{result}}' bindtap='toProductDetail' wx:for="{{productData}}" wx:for-item="result" wx:key="{{result.id}}">
            <image mode="aspectFill" src='{{result.imagePath}}?x-oss-process=style/preview'></image>
            <view class='product_items2_view1'>
              <text class='product_name'>{{result.name}}</text>
              <text class='location_name' wx:if="{{result.longitude>0}}">{{result.location}}</text>
              <text class='location_name' wx:else>{{result.description}}</text>
              <scroll-view class='tags_content' scroll-x>
                <text class='tags_item' wx:if="{{result.tagArray}}" wx:for='{{result.tagArray}}' wx:for-item="tags" wx:key='{{index}}'>{{tags}}</text>
              </scroll-view>
              <view class='product_price'>
                ￥{{result.price}}
                <text wx:if='{{result.unitShow}}' style='color:#bbb;font-size:24rpx;margin-left:4rpx;letter-spacing:4rpx;'>/{{result.unitShow}}</text>
              </view>
            </view>
            
          </view>
        </block>

        <block wx:else>
          <view class="noproduct">
            <image mode="widthFix" src='/images/icons/no-product.png'></image>
            <text>没有相关商品</text>
          </view>
        </block>
      </view>
    </block> -->


    <!-- <block wx:if='{{ProductshowWay == 1}}'> -->
     <scroll-view class="product_page_container2" :style="'height:' + (ProductshowWay==1? '100%':'')">
          <map class="mapItem" id="map" :longitude="localPoint.longitude" :latitude="localPoint.latitude" scale="14" @controltap="controltap" :markers="markers" @markertap="markertap" @regionchange="regionchange" show-location="true" style="width: 100%; height: 830rpx;" @tap="hiddenProInfo">
            <cover-view class="play">
               <image class="img" src="../../static/icon/center.png" style="width:80rpx;height:80rpx;"></image>
            </cover-view>
          </map>
          <view class="bottom_tap">
            <view class="return_index">
              <image src="http://image1.sansancloud.com/xianhua/2018_9/13/16/50/14_226.jpg" class="return_index_img" @tap="toIndex"></image>
            </view>
            <view class="location">
              <image src="http://image1.sansancloud.com/xianhua/2018_9/13/16/50/14_232.jpg" class="location_img" @tap="clickcontrol"></image>
            </view>
          </view>
          <!-- 时间搜索 -->
          <view class="time_select_block">
            <view class="time_select_item">
              <picker mode="date" :value="date" @change="bindDateChange" style="width:100%;">
                <view class="picker">
                  <text v-if="searchData.dateStr">{{searchData.dateStr}}</text>
                  <text v-else class="picker_tip">请选择日期</text>
                </view>
              </picker>
              <image class="time_icon" src="http://image1.sansancloud.com/xianhua/2019_7/3/14/57/22_469.jpg?x-oss-process=style/preview_120"></image>
            </view>
            <view class="time_select_item">
              <picker mode="time" :value="date" @change="bindTimeChange" style="width:100%;">
                <view class="picker">
                  <text v-if="searchData.startTimeStr">{{searchData.startTimeStr}}</text>
                  <text v-else class="picker_tip">请选择开始时间</text>
                </view>
              </picker>
              <image class="time_icon" src="http://image1.sansancloud.com/xianhua/2019_7/3/15/27/17_612.jpg?x-oss-process=style/preview_120"></image>
            </view>
            <view class="sure_select_result" :style="'background:' + setting.platformSetting.defaultColor" data-link="near_shops.html" @tap="tolinkUrl">
              <text>立即找场</text>
            </view>
          </view>
          <cover-view class="product_data" v-if="venueDetail!=null">
            <cover-view class="product_info">
              <cover-image class="product_info_left" :src="(venueDetail.shopInfo.shopLogo+'?x-oss-process=style/preview_120')"></cover-image>
              <cover-view class="product_info_center">
                <cover-view class="product_info_name">{{venueDetail.shopInfo.shopName}}</cover-view>
                <cover-view class="product_info_service_time">
                  <cover-image class="product_info_service_time_img" src="http://image1.sansancloud.com/santigongxiang/2018_10/10/18/22/0_933.jpg"></cover-image>
                  <cover-view class="product_info_service_time_value">{{venueDetail.shopInfo.shopTag}}</cover-view>
                </cover-view>
                <cover-view class="product_info_service_addr">
                  <cover-image class="product_info_service_addr_img" src="http://image1.sansancloud.com/xianhua/2018_9/13/17/57/21_219.jpg"></cover-image>
                  <cover-view class="product_info_service_addr_value" style="width:96%; word-break: break-all;text-overflow: ellipsis;white-space: nowrap;">{{venueDetail.shopInfo.shopLocation}}</cover-view>
                </cover-view>
              </cover-view>
              <cover-view class="product_info_right" :data-link="'near_shop_page.html?addShopId=' + venueDetail.shopInfo.id" @tap="tolinkUrl">
                <cover-view class="line"></cover-view>
                <cover-image src="http://image1.sansancloud.com/xianhua/2018_9/13/20/11/36_801.jpg?x-oss-process=style/preview_120" class="navigation"></cover-image>
              </cover-view>
            </cover-view>
          </cover-view>
      </scroll-view>
    <!-- </block> -->
  

</view>
</template>

<script>

export default {
  data() {
    return {
      setting: null,
      // setting   
      venueData: [],
      // 商品数据 
      venueType: [],
      sysWidth: 320,
      //图片大小
      positionTab: '',
      ProductshowWay: 1,
      // ProductshowWay列表显示方法 (默认显示地图)
      localPoint: {
        longitude: '0',
        latitude: '0'
      },
      venueDetail: null,
      searchData: {},
      shopName: '',
      markers: [{
        iconPath: "../../images/icon/mapItem.png",
        id: 0,
        width: 20,
        heigth: 20,
        latitude: 26.060701172100124,
        longitude: 119.30130341796878
      }],

      /* 全部参数 */
      params: {
        page: 1,
        shopName: "",
        venuesType: "",
        latitude: '0',
        longitude: '0'
      },
      listPage: {
        page: 1,
        pageSize: 0,
        totalSize: 0,
        curpage: 1
      },
      currentItem: ""
    };
  },

  components: {},
  props: {},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    that.initSetting();
    wx.getLocation({
      type: 'gcj02',
      //返回可以用于wx.openLocation的经纬度
      success: function (res) {
        console.log(res);
        that.localPoint.latitude = res.latitude;
        that.localPoint.longitude = res.longitude;
        that.params.latitude = res.latitude;
        that.params.longitude = res.longitude;
        console.log("options", options);

        for (let i in options) {
          for (let j in that.params) {
            if (i.toLowerCase() == j.toLowerCase()) {
              that.params[j] = options[i];
            }
          }
        }

        that.setData({
          params: that.params,
          localPoint: that.localPoint
        });
        console.log(that.params);
        that.getVenueType(); // that.getData();
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.listPage.page = 1;
    this.params.page = 1;
    this.getData(this.params, 2);
    wx.showNavigationBarLoading();
    wx.hideNavigationBarLoading(); //完成停止加载

    wx.stopPullDownRefresh(); //停止下拉刷新
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var that = this;

    if (that.listPage.totalSize > that.listPage.curPage * that.listPage.pageSize) {
      that.listPage.page++;
      that.params.page++;
      this.getData(this.params);
    }
  },

  /**
     * 用户点击右上角分享
     */
  onShareAppMessage: function (res) {
    console.log(res, getApp().globalData.miniIndexPage);
    return getApp().globalData.shareForFx2(getApp().globalData.miniIndexPage);
  },
  methods: {
    getVenueType: function () {
      var customIndex = getApp().globalData.AddClientUrl("/wx_get_venues_types.html"); // wx.showLoading({
      //   title: 'loading'
      // })

      getApp().globalData.showToastLoading('loading', true);
      var that = this;
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          wx.hideLoading();
          console.log("getVenueType", res.data);

          if (res.data.errcode == 0) {
            that.setData({
              venueType: res.data.relateObj.result
            });
          } else {
            that.setData({
              venueType: that.venueType
            });
          }

          if (res.data.relateObj.result.length != 0) {
            that.bindTypeItem(res.data.relateObj.result[0].id);
          } // that.data.venueType.unshift({ id:  0, name: "全部" })


          for (let i = 0; i < that.venueType.length; i++) {
            that.venueType[i].colorAtive = '#888';
          }

          that.venueType[0].colorAtive = that.setting.platformSetting.defaultColor;
          that.venueType[0].active = true;
          that.setData({
            venueType: that.venueType
          });
          console.log("that.data.venueType", that.venueType);
          wx.hideLoading();
        },
        fail: function (res) {
          console.log("fail");
          wx.hideLoading();
          getApp().globalData.loadFail();
        }
      });
    },

    toIndex() {
      getApp().globalData.toIndex();
    },

    clickcontrol(e) {
      //回到定位的
      let mpCtx = wx.createMapContext("map");
      mpCtx.moveToLocation();
    },

    getCenterPoint(callback) {
      let that = this;
      var mapCtx = wx.createMapContext('map');
      mapCtx.getCenterLocation({
        success: function (res) {
          console.log('res', res);
          that.params.latitude = res.latitude;
          that.params.longitude = res.longitude;
          that.setData({
            params: that.params
          });

          if (callback) {
            callback(that.params, 2);
          }
        }
      }); //获取当前地图的中心经纬度
    },

    regionchange(e) {
      console.log('===regionchange===', e);

      if (e.type == 'end') {
        if (e.causedBy == 'scale') {
          console.log('====scale====');
        } else if (e.causedBy == 'drag') {
          console.log('====drag====');
          this.getCenterPoint(this.getData);
        } else {
          console.log('====all====');
          this.getCenterPoint(this.getData);
        }
      }
    },

    markertap(e) {
      console.log(e.markerId);
      this.toProductDetailMap(e.markerId);
    },

    controltap(e) {
      console.log(e);
    },

    hiddenProInfo(e) {
      console.log(e);
      this.setData({
        venueDetail: null
      });
    },

    bindDateChange: function (e) {
      console.log('bindDateChange发送选择改变，携带值为', e.detail.value);
      let searchData = this.searchData;
      searchData.dateStr = e.detail.value;
      this.setData({
        searchData: searchData
      });
    },
    bindTimeChange: function (e) {
      console.log('bindTimeChange发送选择改变，携带值为', e.detail.value);
      let searchData = this.searchData;
      searchData.startTimeStr = e.detail.value;
      this.setData({
        searchData: searchData
      });
    },
    sureSelectResult: function (e) {
      console.log("=====sureSelectResult=====", e);
    },

    /* 点击分类大项 */
    bindTypeItem: function (event) {
      console.log(event);
      let type = event.currentTarget ? event.currentTarget.dataset.type.id : event;
      let that = this;

      for (let i = 0; i < that.venueType.length; i++) {
        if (that.venueType[i].id == type) {
          that.venueType[i].active = true;
          that.venueType[i].colorAtive = that.setting.platformSetting.defaultColor;
          that.setData({
            currentItem: that.venueType[i]
          });
        } else {
          that.venueType[i].active = false;
          that.venueType[i].colorAtive = '#888';
        }
      }

      that.setData({
        venueType: that.venueType
      });
      that.listPage.page = 1;
      that.params.page = 1;

      if (type == "0") {
        that.params.venuesType = 0;
        that.getData();
        var allItem = {
          id: ""
        };
      } else {
        that.params.venuesType = type;
        that.setData({
          venueDetail: null
        });
        that.getData(); //}
      }
    },

    /* 获取数据 */
    getData: function () {
      var that = this;
      let params = that.params;

      if (JSON.stringify(that.searchData) != '{}') {
        params = Object.assign({}, params, that.searchData);
      }

      var customIndex = getApp().globalData.AddClientUrl("/more_near_shops.html", params); // wx.showLoading({
      //   title: 'loading'
      // })

      getApp().globalData.showToastLoading('loading', true);
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          wx.hideLoading();
          console.log(res.data);
          let resData = res.data.relateObj;
          that.listPage.pageSize = resData.pageSize;
          that.listPage.curPage = resData.curPage;
          that.listPage.totalSize = resData.totalSize;
          let dataArr = that.venueData;
          let tagArray = [];

          if (that.params.page == 1) {
            dataArr = [];
          }

          if (!resData.result || resData.result.length == 0) {
            that.setData({
              venueData: null
            });
          } else {
            if (dataArr == null) {
              dataArr = [];
            }

            dataArr = dataArr.concat(resData.result);

            for (let i = 0; i < dataArr.length; i++) {
              if (dataArr[i].shopTag && dataArr[i].shopTag != '') {
                tagArray = dataArr[i].shopTag.slice(1, -1).split("][");
                dataArr[i].tagArray = tagArray;
              }
            }

            that.setData({
              venueData: dataArr
            });
          }

          if (dataArr.length != 0) {
            that.toProductDetailMap(dataArr[0].id);
          }

          that.setData({
            markers: that.venueData
          });
          let mapIcon = "";
          console.log("====that.params.venuesType====", that.params.venuesType, that.venueType);

          if (that.params.venuesType && that.params.venuesType != 0) {
            console.log("有venuesType");

            for (let i = 0; i < that.venueType.length; i++) {
              if (that.params.venuesType == that.venueType[i].id) {
                console.log("获取Icon", that.venueType[i].icon);
                mapIcon = that.venueType[i].icon;
              }
            }
          }

          console.log("====mapIcon====", mapIcon);
          let conut = 0;

          if (that.markers) {
            for (let i = 0; i < that.markers.length; i++) {
              if (mapIcon) {
                that.downProIcon(mapIcon, function (url) {
                  conut++;
                  that.markers[i].iconPath = url;
                  that.markers[i].width = 32;
                  that.markers[i].height = 32;

                  if (conut == that.markers.length) {
                    that.setData({
                      markers: that.markers
                    });
                    console.log('==that.data.markersHave===', that.markers);
                  }
                });
              } else {
                conut++;
                that.markers[i].iconPath = '../../images/icon/mapItem.png';
                that.markers[i].width = 32;
                that.markers[i].height = 32;

                if (conut == that.markers.length) {
                  that.setData({
                    markers: that.markers
                  });
                  console.log('==that.data.markers===', that.markers);
                }
              }
            }
          }

          wx.hideLoading();
        },
        fail: function (res) {
          console.log("fail");
          wx.hideLoading();
          getApp().globalData.loadFail();
        }
      });
    },
    downProIcon: function (url, callback) {
      var _this = this;

      if (getApp().globalData.mapProIconArray[encodeURIComponent(url)]) {
        console.log('已存在', encodeURIComponent(url));
        callback(getApp().globalData.mapProIconArray[encodeURIComponent(url)]);
        return;
      }

      wx.downloadFile({
        url: url.replace('http', 'https'),
        success: function (res) {
          console.log('下载图片', res);

          if (res.statusCode == 200) {
            callback(res.tempFilePath);
            getApp().globalData.mapProIconArray[encodeURIComponent(url)] = res.tempFilePath;
          }
        }
      });
    },

    /* 查找商品 */
    getSearchShopName: function (e) {
      console.log(e);

      if (e.detail.value) {
        this.params.shopName = e.detail.value;
      } else {
        this.params.shopName = '';
      }

      this.setData({
        shopName: this.params.shopName
      });
      this.getData();
    },

    /* 商品显示方法 */
    toMy: function () {
      wx.navigateTo({
        url: '/pagesTwo/aikucun_userinfo/index'
      });
    },
    tolinkUrl: function (event) {
      let that = this;
      console.log("e.currentTarget.dataset.link=====", event.currentTarget.dataset.link);
      let linkUrl = event.currentTarget.dataset.link;

      if (linkUrl == 'near_shops.html') {
        linkUrl = linkUrl + "?venuesType=" + that.params.venuesType + "&dateStr=" + (that.searchData.dateStr || '') + "&startTimeStr=" + (that.searchData.startTimeStr || '');
      }

      getApp().globalData.linkEvent(linkUrl);
    },
    toProductDetailMap: function (id) {
      console.log("--------toProductDetailMap------", id);
      let customIndex = getApp().globalData.AddClientUrl('/shop_detail_' + id + '.html');
      var that = this;
      that.setData({
        venueDetail: null
      });
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          console.log(res.data);
          let venueDetail = res.data.result;

          if (venueDetail.shopInfo.shopTag && venueDetail.shopInfo.shopTag != '') {
            let tagArray = venueDetail.shopInfo.shopTag.slice(1, -1).split("][");
            venueDetail.shopInfo.tagArray = tagArray;
          }

          that.setData({
            venueDetail: venueDetail
          });
        },
        fail: function (res) {
          console.log("fail");
          getApp().globalData.loadFail();
        },
        complete: function () {}
      });
    },

    initSetting() {
      this.setData({
        setting: getApp().globalData.setting
      });

      for (let i = 0; i < this.setting.platformSetting.categories.length; i++) {
        this.setting.platformSetting.categories[i].colorAtive = '#888';
      }

      this.setting.platformSetting.categories[0].colorAtive = this.setting.platformSetting.defaultColor;
      this.setData({
        setting: this.setting
      });
    },

    setData: function (obj) {
      let that = this;
      let keys = [];
      let val, data;
      Object.keys(obj).forEach(function (key) {
        keys = key.split('.');
        val = obj[key];
        data = that.$data;
        keys.forEach(function (key2, index) {
          if (index + 1 == keys.length) {
            that.$set(data, key2, val);
          } else {
            if (!data[key2]) {
              that.$set(data, key2, {});
            }
          }

          data = data[key2];
        });
      });
    }
  }
};
</script>
<style>
@import "./index.css";
</style>